package com.zkingsoft.actions.admin;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.anotations.RemoveRequestToken;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.exception.GlobleException;
import com.zkingsoft.model.Bonus;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.plugin.util.ExcelImport;
import com.zkingsoft.plugin.util.ExcelUtil;
import com.zkingsoft.plugin.util.ExcelUtil.ViewExcel;
import com.zkingsoft.plugin.util.FileDownload;
import com.zkingsoft.plugin.util.FileUtils;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.BonusService;

/**
 * 奖金名目controller
 * @date 2016-11-17 11:32
 */
@Controller
@RequestMapping(value = "admin/bonus")
public class BonusController extends BaseController{

	@Resource
	private BonusService bonusService;
	
	/**
	 * 列表显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(Bonus bonus, PaginationVO pageVo) {
		return showList(bonusService, bonus, pageVo);
	}
   	
	/**
	 * 新增或者修改页面
	 */   
	@RemoveRequestToken	
   	@RequestMapping(value = "/addOrModify")
	public @ResponseBody AjaxResult addOrModify(Bonus bonus) {
		if (bonus.getbId() != null) {
			return modify(bonusService, bonus, "奖金名目");
		} else {
			bonus.setbDate(new Date());
			return add(bonusService, bonus, "奖金名目");
		}
	}
	
   	/**
	 * 进入修改界面
	 */   
	@SaveRequestToken
   	@RequestMapping(value = "/editForm")
	public String editForm(Long id) {
		Bonus bonus;
		if (id != null) {
			bonus = bonusService.findById(id);
			WebUtil.getRequest().setAttribute("obj", bonus);
		}
		return "admin/bonus-form";
	}
   	
   	
   	/**
	 * 删除
	 */  
 	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		return remove(bonusService, keys);
	}
 	
 	/**
 	 * 
 	 * @Description:导出excel
 	 * @author:dingchuan
 	 * @return
 	 * 返回类型 ModelAndView
 	 * @date 2017年2月13日
 	 */
 	@RequestMapping(value = "/exportExcel")
 	public @ResponseBody ModelAndView report(ModelMap model, HttpServletRequest request, HttpServletResponse response,
 			Bonus bonus) {
 	    try {
 	        if (bonus.getbName() != null && !(bonus.getbName().equals(""))) {
 	        	bonus.setbName(java.net.URLDecoder.decode(bonus.getbName(), "UTF-8"));
 	        }
 	    } catch (UnsupportedEncodingException e1) {
 	        e1.printStackTrace();
 	    }
 	    // 查询符合条件的数据
 	    List<Bonus> dataList = bonusService.findByModel(bonus);
 	    //把数据组装成我们要的数据，外面的list表示一行数据，也就是一个对象的信息，对应到excel的一行数据。里面的list表示对象的一个属性，对应excel的单元格
 	    SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
 	    List<List< Object>> list = new ArrayList<>();
 	        for (Bonus obj : dataList) {
 	            List<Object> temp = new ArrayList<>();
 	            temp.add(obj.getbName());
 	            String dateStr = sdf.format(obj.getbDate());
 	           	temp.add(dateStr);
 	            temp.add(obj.getbRemark());
 	            list.add(temp);
 	        }
 	    //调用我们的excel工具类，导出数据
 	    HSSFWorkbook workbook = ExcelUtil.generateExcel("奖金名目列表",
 	            new String[] { "奖金名称","添加时间","备注"}, list);
 	    try {
 	        ViewExcel.buildExcel(null, workbook, request, response, "奖金名目列表.xls");
 	    } catch (Exception e) {
 	        e.printStackTrace();
 	    }
 	    return new ModelAndView(new ViewExcel(), model);
 	}
 	
 	/**
 	 * @Description:下载模板
 	 * @author:dingchuan
 	 * @param response
 	 * @throws Exception
 	 * 返回类型 void
 	 * @date 2017年2月14日
 	 */
 	@RequestMapping(value="/downExcelModel")
   	public void downExcelModel(HttpServletResponse response) throws Exception{
   		String path = WebUtil.getResourceRealPath("WEB-INF/views/admin/bonus_import_model.xlsx");   		
   		FileDownload.fileDownload(response, path, "奖金名目导入模板.xlsx");
   	}
 	
	private static final Logger log = Logger.getLogger(BonusController.class);
 	
 	/**
 	 * @Description:导入excel
 	 * @author:dingchuan
 	 * @param response
 	 * @param request
 	 * @param file
 	 * @return
 	 * 返回类型 AjaxResult
 	 * @date 2017年2月14日
 	 */
 	@RequestMapping(value = "/importData")
	public @ResponseBody AjaxResult importData(HttpServletResponse response, HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file) {
		// 记录成功的导入多少条数据
		int count = 0;
		// 构造对象的集合
		List<Bonus> bonusList = new ArrayList<Bonus>();
		response.setContentType("text/html;charset=UTF-8");
		String fileName = file.getOriginalFilename();
		String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
		if (!extension.equals("xls") && !extension.equals("xlsx")) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "请选择excel文件！！！");
		}
		String dirPath = request.getSession().getServletContext().getRealPath("/") + "fileupload";
		File fileDir = new File(dirPath);
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
		try {
			if (!fileDir.exists()) {
				if (fileDir.mkdirs()) {
				}
			}
			File saveFile = new File(dirPath + "/" + fileName);
			file.transferTo(saveFile);
			List<List<Object>> list = ExcelImport.readExcel(saveFile, fileName, null, 2);
			// 由于读取excel的工具类会从标题行开始读取，因此，list=null或者size=1表示只有标题行说明没有数据可以导入
			if (list == null || list.size() <= 1) {
				throw new GlobleException("没有数据可导入");
			}
			for (int i = 2; i < list.size(); i++) {
				Bonus bonus = new Bonus();//每一行
				List<Object> objList = list.get(i);
				int t = i+1;
				if(objList.get(0)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的奖金名称没有填写");
   	   			}else{
   	   				String bonusName = ((String)objList.get(0)).trim();//奖金名称
   	   				bonus.setbName(bonusName);
   	   			}
				
				if(objList.get(1)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的添加时间没有填写");
   	   			}else{
   	   				String uJobdate = ((String)objList.get(1)).trim();//入学时间
   	   				Date date;
   	   				try {
   	   					date = sdf.parse(uJobdate);
					} catch (Exception e) {
						log.debug(e.toString());
		   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的添加时间填写格式不正确");
					}
   	   			bonus.setbDate(date);
   	   			}
				
				bonus.setbRemark((String)objList.get(2));
				bonusList.add(bonus);
			}
			count =	bonusService.adds(bonusList);
		} catch (IOException e) {
			log.error("导入异常");
		}finally {
			FileUtils.deleteDir(fileDir);
		}
		if (count > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "成功导入" + count + "条数据!");
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!");
		}
	}
 	
 	
}